package com.sss.springcloud.ribbon;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sss
 * @date 2020-03-07 10:02
 **/
@Component
public class CustomLoadBalance implements MyLoadBalance {

   private AtomicInteger atomicInteger= new AtomicInteger(0);

    public ServiceInstance getServiceInstance(List<ServiceInstance> instances) {
        if (instances==null||instances.size()<=0) {
            return  null;
        }
        int index = getIndex() % instances.size();
        return instances.get(index);
    }

    public final int getIndex(){
        int current,next;
        current=atomicInteger.get();
        next=current>=Integer.MAX_VALUE?0:current+1;
        while (!this.atomicInteger.compareAndSet(current,next)){

        }
        System.out.println("第几次访问，next的次数为："+next);
        return next;
    }

}
